 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package RRHH_controlador;

import Conexion.Conexion;
import RRHH_Modelo.RHH_BONO;
import RRHH_Modelo.RHH_BONO_USUARIO;
import RRHH_Modelo.RHH_PERSONA;
import RRHH_Modelo.RHH_USUARIO;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


    /**
 *
 * @author equipo_4
 */
@WebServlet(name = "RRHH_OTROS_INGRESOS_CONTROLLER", urlPatterns = {"/RRHH_OTROS_INGRESOS_CONTROLLER"})
public class RRHH_OTROS_INGRESOS_CONTROLLER extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet RRHH_OTROS_INGRESOS_CONTROLLER</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet RRHH_OTROS_INGRESOS_CONTROLLER at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            RHH_USUARIO usuario = ((RHH_USUARIO)request.getSession().getAttribute("usr"));
            Conexion con = new Conexion(usuario.getPASSWORD(), usuario.getPASSWORD());
        try {            
                String evento = request.getParameter("proceso");
                String html="";
                switch(evento)
                {
                    case "llenar":
                        html=llenar(request,con);
                        break;                
                    case "buscarEmpleado":
                        html=buscarEmpleado(request,con);
                        break;                
                    case "eliminar":
                        html=eliminar(request,con);
                        break;                
                    case "insertar":
                        html=insertar(request,con);
                        break;                
                    case "insertarbono":
                        html=insertarbono(request,con);
                        break;                
                    case "eliminarbono":
                        html=eliminarbonos(request,con);
                        break;                
                    
                }
                
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/plain");
                response.getWriter().write(html);
                con.Close();
        } catch (SQLException ex) {
            response.setCharacterEncoding("UTF-8");
                response.setContentType("text/plain");
                response.getWriter().write("false");
                con.Close();
        }
    } 

    private String insertarbono(HttpServletRequest request, Conexion con) throws SQLException {
        String desc = request.getParameter("desc");
        String deduc = request.getParameter("impuesto");
        int imp=0;
        if(deduc!=null)
            imp = 1;
        RHH_BONO bono = new RHH_BONO(0, desc, imp);
        bono.setCon(con);
        int id=bono.Insertar();        
        return "<option value='"+id+"' selected>"+desc+"</option>";
    }
      private String eliminarbonos(HttpServletRequest request, Conexion con) throws SQLException {
        try
        {
            int id = Integer.parseInt(request.getParameter("idbono"));
            RHH_BONO bono =new RHH_BONO(con).Buscar(id);
            bono.EliminarXid();
            return true+"";
        }
        catch(Exception e)
        {
            return false+"";
        }
    }
     private String insertar(HttpServletRequest request, Conexion con) throws SQLException {
        int id = Integer.parseInt(request.getParameter("id"));
        String motivo = request.getParameter("motivo");
        Double monto = Double.parseDouble(request.getParameter("monto"));
        int idbono = Integer.parseInt(request.getParameter("bono"));
        String fini = request.getParameter("fini");
        int meses = Integer.parseInt(request.getParameter("meses"));
        
        String mes1 = fini.substring(3,5);
        String ano1 = fini.substring(6,10);
        
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.MONTH, Integer.parseInt(mes1)-1);
        cal.set(Calendar.YEAR, Integer.parseInt(ano1));  
        Date algo = cal.getTime();
        Calendar cal2 = cal;
        cal2.add(Calendar.MONTH, (meses-1));
        RHH_BONO_USUARIO bonouss = new RHH_BONO_USUARIO(0,id, idbono, motivo, monto, algo, cal2.getTime());
        bonouss.setCon(con);
        int idn=bonouss.Insertar();
        RHH_BONO b = new RHH_BONO(con).Buscar(idbono);
        SimpleDateFormat format = new SimpleDateFormat("MM/yyyy");
        return "<tr><td>"+motivo+"</td><td>"+monto+"</td><td>"+b.getDESCRIPCION()+"</td><td>"+meses+"</td><td>"+format.format(algo)+"</td><td>"+format.format(cal2.getTime())+"</td><td><a href='#' onclick='eliminar( "+idn+",this);'>ELIMINAR</a></td></tr>";
    }
    private String llenar(HttpServletRequest request, Conexion con) throws SQLException {
        int id = Integer.parseInt(request.getParameter("id"));
        String html = "";
        List<RHH_BONO_USUARIO> lista = new RHH_BONO_USUARIO(con).TodosxUsuario(id);

        for(RHH_BONO_USUARIO bono:lista) {
            Calendar calini = new GregorianCalendar();
            Calendar califin = new GregorianCalendar();
            calini.setTime(bono.getFECHA_INId());
            califin.setTime(bono.getFECHA_FINd());            
            int meses=1;
            while(calini.before(califin))
            {
                calini.add(Calendar.MONTH, 1);
                meses++;
            }
            SimpleDateFormat formato = new SimpleDateFormat("MMMM/yyyy");
            calini.setTime(bono.getFECHA_INId());
            RHH_BONO bon = new RHH_BONO(con).Buscar(bono.getID_BONO());
            html+="<tr>";
            html+="<td>"+bono.getMOTIVO()+"</td>";
            html+="<td>"+bono.getMONTO()+"</td>";
            html+="<td>"+bon.getDESCRIPCION()+"</td>";
            html+="<td>"+meses+"</td>";
            html+="<td>"+formato.format(calini.getTime())+"</td>";
            html+="<td>"+formato.format(califin.getTime())+"</td>";
            html+="<td><a href='#' onclick='eliminar("+bono.getID()+",this);'>ELIMINAR</a></td>";
            html+="</tr>";
        }
        return html ;
    }
    private String buscarEmpleado(HttpServletRequest request, Conexion con) throws SQLException {
        String text = request.getParameter("text");
        RHH_PERSONA persona = new RHH_PERSONA(con);
        RHH_USUARIO usuario = new RHH_USUARIO(con);
        List<RHH_USUARIO> lista = usuario.buscarempleado(text);
        String html = "";
        for (int i = 0; i < lista.size(); i++) {
            persona = persona.BuscarxID_Usuario(lista.get(i).getID());
            usuario=usuario.BuscarXidPersona(persona.getID());
            String src = "../img/imagen3.jpg";
            String nombre = persona.getPRIMER_NOMBRE() + " ";
            if (persona.getSEGUNDO_NOMBRE() != null || !persona.getSEGUNDO_NOMBRE().equals("null")) {
                nombre += persona.getSEGUNDO_NOMBRE() + " ";
            }
            nombre += persona.getPRIMER_APELLIDO();
            if (persona.getSEGUNDO_APELLIDO() != null || !persona.getSEGUNDO_APELLIDO().equals("null")) {
                nombre += " " + persona.getSEGUNDO_APELLIDO() + " ";
            }
            
            html += "<div  onclick=\"abrirpop(this,'" + usuario.getID() + "','" + nombre + "',0)\" style=\"padding: 5px; width: 106px; background: none repeat scroll 0% 0% white; border-radius: 7px; height: 135px; margin: 5px; float:left;\">\n"
                    + "<div class=\"centrado negrilla\" class='ci'>" + persona.getCI() + "</div>\n"
                    + "<div style=\"height: 80px; width: 104px;\">\n"
                    + "<img style=\"width: 100%; height: 100%;\" alt=\"\" src=\"" + src + "\" data-ci='" + persona.getCI()+ "' data-foto='"+persona.getFOTO()+"' class='imagen'>\n"
                    + "</div>\n"
                    + "<div class=\"centrado\">" + nombre + "</div>\n"
                    + "                   </div>";
        }
        return html;
    }
    private String eliminar(HttpServletRequest request, Conexion con) throws SQLException {
        try
        {
            int bono= Integer.parseInt(request.getParameter("bono"));
            return new RHH_BONO_USUARIO(con).eliminar(bono)+"";
        }
        catch(Exception e)
        {
            return false+"";
        }
    }
   
        
}
